﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using System.Text;

namespace VSM.Parts
{
    public partial class InventoryTransfer : System.Web.UI.Page
    {
        #region Fields
        private string TblHeaderName = "OWTR";
        private string TblLineName = "WTR1";
        private string CurrentPageUrl = "/Business/Parts/Inventory/InventoryTransfer.aspx";

        private string HeaderKeyName = "DocEntry";
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.Private);

            if (Session[Utils.AppConstants.ID_User] == null
                || Session[Utils.AppConstants.Password] == null
                || Session[Utils.AppConstants.ID_Dealer] == null)
            {
                Response.Redirect("../../../Login.aspx");
            }

            if (Session[Utils.AppConstants.ID_Dealer].ToString() != "VSM")
            {
                this.ddl_InternalTransfer.Enabled = false;
                this.ddl_InternalTransfer.Enabled = false;
            }
            if (!IsPostBack)
            {
                ClearScreen();
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                if (dbType != "VSM")
                {
                    this.ddl_Transfer.Items.Add(new ListItem("Xuất cho xưởng dịch vụ", "XDV"));
                }
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                //if (dbType != "VSM")
                //{
                //    this.lblDebitNote.Visible = false;
                //    this.txtDebitNoteNo.Visible = false;
                //    this.ddlTime.Visible = false;
                //    this.txtBillNumber.Visible = false;
                //    this.lblBillNumber.Visible = false;
                //}
                String itransId = Request.QueryString["itrans_id"];
                if (!String.IsNullOrEmpty(itransId))
                {
                    LoadData(itransId, ConvertDocType.Get2String(DocType.TRANSFER));
                    SetScreenStatus("Close");
                }
                else
                {
                    LoadDefault();
                    SetScreenStatus("New");
                }

                String BaseEntry = Request.QueryString["base_entry"];
                if (!String.IsNullOrEmpty(BaseEntry))
                {
                    String BaseType = Request.QueryString["base_type"];
                    LoadData(BaseEntry, BaseType);
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvWTR1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            this.grvWTR1.PageIndex = e.NewPageIndex;
            DataTable tblITrans = (DataTable)Session["WTR1Table"];
            BindData(tblITrans);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void lnkDelete_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)row.FindControl("lblItemCode");
                DataTable tblITrans = (DataTable)Session["WTR1Table"];
                if (tblITrans != null)
                {
                    DataRow[] rupdate = tblITrans.Select("ItemCode='" + lblItemCode.Text + "'");
                    if (rupdate.Length > 0)
                    {
                        Dictionary<string, string> dicItem = (Dictionary<string, string>)Session["ChosenItem"];
                        if (dicItem != null)
                        {
                            if (dicItem.ContainsKey(rupdate[0]["ItemCode"].ToString()))
                            {
                                dicItem.Remove(rupdate[0]["ItemCode"].ToString());
                            }
                        }
                        tblITrans.Rows.Remove(rupdate[0]);
                    }
                    this.grvWTR1.EditIndex = -1;
                    BindData((DataTable)Session["WTR1Table"]);
                    CalcTotal(((DataTable)Session["WTR1Table"]));
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        /// <param name="sender"></param>
        protected void grvWTR1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");
                e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
                e.Row.Attributes["style"] = "cursor:pointer";
                int index = 0;

                if (ViewState["rowindex"] != null && Session["POTable"] != null)
                {
                    index = Convert.ToInt32(ViewState["rowindex"].ToString());
                    int rowCount = ((DataTable)Session["WTR1Table"]).Rows.Count;
                    if ((index + 1) <= this.grvWTR1.Rows.Count)
                    {

                    }
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        private void DisableControl()
        {

        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtOrderQuantity_OnTextChanged(object sender, EventArgs e)
        {
            try
            {
                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                this.lblError.Visible = false;
                GridViewRow row = (GridViewRow)((DataControlFieldCell)((TextBox)sender).Parent).Parent;
                ViewState["rowindex"] = row.RowIndex;
                TextBox txtQuantity = (TextBox)row.FindControl("txtQuantity");
                if (txtQuantity.Text.Trim().Length == 0)
                {
                    ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", "alert('Pls input quantity');", true);
                    txtQuantity.Focus();
                    return;
                }

                Label lblNo = (Label)row.FindControl("lblNo");
                DataTable tblITrans = (DataTable)Session["WTR1Table"];

                if (tblITrans != null)
                {
                    DataRow[] rupdate = tblITrans.Select("No=" + lblNo.Text);
                    if (rupdate.Length > 0)
                    {
                        rupdate[0]["Quantity"] = GF.FormatNumeric(GF.ResetFormatNumeric(txtQuantity.Text), "QtyDec");
                    }
                }

                this.grvWTR1.EditIndex = -1;

                BindData(tblITrans);
                CalcTotal(tblITrans);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblData"></param>
        private void BindData(DataTable tblData)
        {
            Session["WTR1Table"] = tblData;
            this.grvWTR1.DataSource = tblData;
            this.grvWTR1.DataBind();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                base.OnLoadComplete(e);
                if (this.Request["__EVENTARGUMENT"] != null && this.Request["__EVENTARGUMENT"].ToString() != "")
                {
                    DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text);
                    DataTable tblITrans = (DataTable)Session["WTR1Table"];
                    string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                    GridViewRow grdvRow = null;

                    switch (this.Request["__EVENTARGUMENT"].ToString())
                    {
                        case "SelectItem":
                            this.lblError.Visible = false;
                            if (tblITrans != null)
                            {
                                Dictionary<string, string> dicItem = Session["ChosenItem"] != null ? (Dictionary<string, string>)Session["ChosenItem"] : null;
                                if (dicItem != null)
                                {
                                    MasterData obj = new MasterData();
                                    string lstItemCode = string.Empty;

                                    foreach (KeyValuePair<string, string> item in dicItem)
                                    {
                                        if (string.IsNullOrEmpty(lstItemCode))
                                            lstItemCode = "'" + item.Key + "'";
                                        else
                                            lstItemCode = lstItemCode + ", '" + item.Key + "'";
                                    }

                                    DataSet dsItem = obj.GetItemsByItemCodeList(dbType, Utils.AppConstants.ID_Dealer, lstItemCode);
                                    GetDefault defaultWS = new GetDefault();

                                    if (dsItem != null && dsItem.Tables.Count > 0)
                                    {
                                        foreach (DataRow dr in dsItem.Tables[0].Rows)
                                        {
                                          
                                            DataSet defaultInfo = defaultWS.GetPartsDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                                               this.txtCustomerCode.Text, dr["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.PARTS, "4");
                                            if (defaultInfo != null && defaultInfo.Tables != null && defaultInfo.Tables[0].Rows.Count == 1)
                                                tblITrans = AddNewItem(tblITrans, defaultInfo.Tables[0].Rows[0], dr["ItemCode"].ToString(), dr["ItemName"].ToString(), dr["U_Model"].ToString(), dr["U_Color"].ToString()
                                                    , defaultInfo.Tables[0].Rows[0]["UomCode"].ToString());
                                            else continue;
                                        }
                                    }
                                }
                            }
                            //ReLoad Data
                            BindData(tblITrans);
                            break;

                        case "SelectBP":
                            ViewState["rowindex"] = -1;
                            this.lblError.Visible = false;
                            grdvRow = Session["ChosenBP"] != null ? (GridViewRow)Session["ChosenBP"] : null;

                            this.txtCustomerCode.Text = ((Label)grdvRow.FindControl("lblCardCode")).Text;
                            this.txtCustomerName.Text = ((Label)grdvRow.FindControl("lblCardName")).Text;
                            this.txtContactPerson.Text = ((Label)grdvRow.FindControl("lblCntctPrsn")).Text;
                            if (tblITrans != null) tblITrans.Rows.Clear();
                            Session["ChosenBP"] = null;
                            this.txtItemCode.Enabled = 
                            this.btnAddItems.Enabled = true;
                            if (dbType == "VSM")
                            {
                                FormatSONumber(this.txtCustomerCode.Text);
                            }
                            break;

                        case "SelectWhsFrom":
                            this.lblError.Visible = false;
                            grdvRow = Session["ChosenWhs"] != null ? (GridViewRow)Session["ChosenWhs"] : null;
                            this.txtFromWhsCode.Text = ((Label)grdvRow.FindControl("lblWhsCode")).Text;
                            this.txtFromWhsName.Text = ((Label)grdvRow.FindControl("lblWhsName")).Text;

                            Session["ChosenWhs"] = null;
                            break;

                        case "SelectWhsTo":
                            this.lblError.Visible = false;
                            grdvRow = Session["ChosenWhs"] != null ? (GridViewRow)Session["ChosenWhs"] : null;
                            this.txtToWhsCode.Text = ((Label)grdvRow.FindControl("lblWhsCode")).Text;
                            this.txtToWhsName.Text = ((Label)grdvRow.FindControl("lblWhsName")).Text;
                            Session["ChosenWhs"] = null;
                            break;

                        case "SelectDocList":
                            GridViewRow rowDocList = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string DocNum = ((Label)rowDocList.FindControl("lblDocNum")).Text;
                            string doctype = ((Label)rowDocList.FindControl("lblDocType")).Text;
                            this.hdnDocEntry.Value = DocNum;
                            LoadData(DocNum, doctype);
                            this.txtBillNumber.Enabled = true;
                            this.txtDeliveryDate.Enabled = true;
                            this.ImageButton1.Enabled = true;
                            this.ddlTime.Enabled = true;
                            break;
                        case "SelectDraftDocList":
                            GridViewRow rowDraft = Session["ChosenDocList"] != null ? (GridViewRow)Session["ChosenDocList"] : null;
                            string DraftDocEntry = ((Label)rowDraft.FindControl("lblDocEntry")).Text;
                            string DraftDocType = ((Label)rowDraft.FindControl("lblDocType")).Text;
                            this.hdnBaseType.Value = DraftDocType;
                            this.hdnDocEntry.Value = DraftDocEntry;
                            this.hdnIsDraft.Value = "1";
                            LoadDraftData(DraftDocEntry);
                            this.txtBillNumber.Enabled = true;
                            this.txtDeliveryDate.Enabled = true;
                            this.ImageButton1.Enabled = true;
                            this.ddlTime.Enabled = true;
                            break;
                        case "SelectOSRI":
                            GridViewRow rowOSRI = Session["ChosenOSRI"] != null ? (GridViewRow)Session["ChosenOSRI"] : null;
                            Label lblItemCode = (Label)rowOSRI.FindControl("lblItemCode");
                            Label lblIntrSerial = (Label)rowOSRI.FindControl("lblIntrSerial");
                            Label lblInDate = (Label)rowOSRI.FindControl("lblInDate");
                            Label lblNotes = (Label)rowOSRI.FindControl("lblNotes");
                            Label lblSysSerial = (Label)rowOSRI.FindControl("lblSysSerial");
                            if (tblITrans != null & tblITrans.Rows.Count > 0)
                            {
                                DataRow[] rCheck = tblITrans.Select("ItemCode='" + lblItemCode.Text + "'");
                                if (rCheck.Length == 1)
                                {
                                    rCheck[0]["SysNumber"] = lblSysSerial.Text;
                                    rCheck[0]["DistNumber"] = lblIntrSerial.Text;
                                    rCheck[0]["InDate"] = lblInDate.Text;
                                    rCheck[0]["Notes"] = lblNotes.Text;
                                }
                                // Reload data
                                BindData(tblITrans);
                            }
                            break;

                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }
        private void FormatSONumber(string CustomerCode)
        {
            this.lblSONumber.Text = string.Empty;
            this.txtSONumber.Text = string.Empty;
            //Format SO Number
            string param1 = string.Empty;
            string param2 = string.Empty;
            string param3 = string.Empty;
            string param4 = string.Empty;
            if (CustomerCode.StartsWith("C"))
            {
                param1 = "D";
                CustomerCode = "0001";
            }
            else
            {
                param1 = "I";
            }

            param2 = DateTime.Now.Date.ToString("yy");
            param3 = int.Parse(DateTime.Now.Date.ToString("MM")).ToString();
            if (param3 == "10") param3 = "x";
            if (param3 == "11") param3 = "y";
            if (param3 == "12") param3 = "z";
            if (param1.Length > 0)
            {
                string soNumber = string.Format("{0}{1}{2}{3}", CustomerCode, param1, param2, param3);
                this.lblSONumber.Text = soNumber;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tblITrans"></param>
        /// <param name="drDefaultLine"></param>
        /// <param name="ItemCode"></param>
        /// <param name="Dscription"></param>
        /// <param name="Model"></param>
        /// <param name="Color"></param>
        /// <param name="unitMsr"></param>
        /// <returns></returns>
        private DataTable AddNewItem(DataTable tblITrans, DataRow drDefaultLine, string ItemCode, string Dscription, string Model, string Color, string unitMsr)
        {
            try
            {
                if (drDefaultLine != null && drDefaultLine.ItemArray.Length > 0)
                {
                    DataRow rowNew = tblITrans.NewRow();
                    rowNew["No"] = (tblITrans.Rows.Count + 1).ToString();
                    rowNew["ItemCode"] = ItemCode;
                    rowNew["Dscription"] = Dscription;
                    rowNew["U_Model"] = Model;
                    rowNew["U_Color"] = Color;
                    rowNew["Quantity"] = 1;
                    rowNew["unitMsr"] = unitMsr;
                    rowNew["FromWhsCod"] = txtFromWhsCode.Text;
                    rowNew["WhsCode"] = txtToWhsCode.Text;

                    DataRow[] rCheck = tblITrans.Select("ItemCode='" + ItemCode + "'");
                    if (rCheck.Length == 0)
                    {
                        tblITrans.Rows.Add(rowNew);
                    }
                }
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return tblITrans;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="tb"></param>
        private void CalcTotal(DataTable tb)
        {
            try
            {
                double documentTotal = 0;
                double gstTotal = 0;
                double subTotal = 0;
                foreach (DataRow row in tb.Rows)
                {
                    subTotal += double.Parse(row["LineTotal"].ToString());
                    if (row["Rate"] != null && row["Rate"].ToString().Length > 0)
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * double.Parse(row["Rate"].ToString())) / 100;
                    }
                    else
                    {
                        gstTotal += (double.Parse(row["LineTotal"].ToString()) * 8.25) / 100;
                    }
                }
                documentTotal += subTotal + gstTotal;

            }
            catch (Exception ex)
            {
                string alert = "alert('Error: " + ex.Message + " ');";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", alert, true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="poDate"></param>
        /// <param name="itemCode"></param>
        /// <param name="venderCode"></param>
        /// <param name="quantity"></param>
        /// <returns></returns>
        private DataSet GetDataItem(DateTime poDate, string itemCode, string venderCode, double quantity)
        {
            try
            {
                MasterData obj = new MasterData();
                DataSet ds = new DataSet();
                ds = null; // obj.GetItem(Session[Utils.AppConstants.ID_User].ToString(), Session[Utils.AppConstants.Password].ToString(), _companyCode, poDate, itemCode, venderCode, quantity);
                return ds;
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
            return null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {


            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }


        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void grvWTR1_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                GridViewRow myRow = e.Row;
                Label lblNo = myRow.FindControl("lblNo") as Label;
                lblNo.Text = (myRow.RowIndex + 1).ToString();

                if (this.hdnStatus.Value == "C")
                {
                    TextBox txtQuantity = myRow.FindControl("txtOrderQuantity") as TextBox;
                    txtQuantity.Enabled = false;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void txtPODate_TextChanged(object sender, EventArgs e)
        {
            try
            {
                //Check Valid Date
                Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text.Trim());
                //this.btnShowPopup.Enabled = true;
            }
            catch
            {
                //this.btnShowPopup.Enabled = false;
            }
        }
        /// <summary>
        /// 
        /// </summary>

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                if (this.txtSONumber.Text.Length == 0)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Please input SO Number!" + "','');", true);
                    this.txtSONumber.Focus();
                    return;
                }
                if (string.IsNullOrEmpty(this.txtDebitNoteNo.Text))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('Missing Debit Note No.','');", true);
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                    this.txtDebitNoteNo.Focus();
                    return;
                }
                else
                {
                    string lsNumAtCard = GF.GetSingleValue(dbType, " SELECT U_DebitNote FROM ODLN WHERE U_DebitNote = '" + this.txtDebitNoteNo.Text.Trim() + "'", "U_DebitNote");
                    if (!string.IsNullOrEmpty(lsNumAtCard))
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('The Debit Note No. existed.','');", true);
                        ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                        this.txtDebitNoteNo.Focus();
                        return;
                    }
                }

                String requestXML = _collectData(false);
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                bool isUpdate = false;
                if (this.hdnDocEntry.Value.Length > 0 && this.hdnIsDraft.Value == string.Empty)
                {
                    isUpdate = true;
                }
                DataSet ds = ts.CreateMarketingDocument(requestXML, ((ulong)DocType.TRANSFER).ToString(), txtTransferNo.Text, isUpdate, dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    //Close Draft
                    if (this.hdnIsDraft.Value == "1" && this.hdnDocEntry.Value.Length > 0)
                    {
                        ts.CloseCancelDocument( ConvertDocType.Get2String(DocType.ALL_DRAFT), this.hdnDocEntry.Value, true, dbType);// thangnv edited 2014/07/22
                    }
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                //SetControlsStatus("Save");
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseCancel(true);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnClose_Click(object sender, EventArgs e)
        {
            CloseCancel(false);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="isClose"></param>
        private void CloseCancel(bool isClose)
        {
            try
            {
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
            }
            this.lblError.Visible = true;
        }

        private void BuildSRNT(ref DataTable dtSRNT, string ItemCode, string SysNumber, string DistNumber, string InDate, string Notes,
            double Quantity, string WhsCode, string DocType, string DocEntry, string DocLineNum)
        {
            if (dtSRNT == null)
            {
                dtSRNT = new DataTable("SRNT");
                dtSRNT.Columns.Add("ItemCode");
                dtSRNT.Columns.Add("SysNumber");
                dtSRNT.Columns.Add("DistNumber");
                dtSRNT.Columns.Add("InDate");
                dtSRNT.Columns.Add("Quantity");
                dtSRNT.Columns.Add("WhsCode");
                dtSRNT.Columns.Add("DocType");
                dtSRNT.Columns.Add("DocEntry");
                dtSRNT.Columns.Add("DocLineNum");
                dtSRNT.Columns.Add("Notes");
            }

            DataRow drSRNT = dtSRNT.NewRow();
            drSRNT["ItemCode"] = ItemCode;
            drSRNT["SysNumber"] = SysNumber;
            drSRNT["DistNumber"] = DistNumber;
            if (InDate.Length > 0 && Utils.AppConstants.isDateTime(InDate))
            {
                drSRNT["InDate"] = Utils.AppConstants.ConvertToDate(InDate).ToString("yyyymmdd");
            }
            else
            {
                drSRNT["InDate"] = DateTime.Now.ToString("yyyymmdd");
            }
            drSRNT["Quantity"] = Quantity;
            drSRNT["WhsCode"] = WhsCode;
            drSRNT["DocType"] = DocType;
            drSRNT["DocEntry"] = DocEntry;
            drSRNT["DocLineNum"] = DocLineNum;
            drSRNT["Notes"] = Notes;

            dtSRNT.Rows.Add(drSRNT);
        }

        public String _collectData(bool isDraft)
        {
            try
            {
                string tableHeader = string.Empty;
                string tableDetail = string.Empty;

                if (!isDraft)
                {
                    tableHeader = "OWTR";
                    tableDetail = "WTR1";
                }
                else
                {
                    tableHeader = "ODRF";
                    tableDetail = "DRF1";
                }

                string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
                //Update table header
                DataTable dtHeader = new DataTable(tableHeader);
                if (!isDraft)
                {
                    dtHeader.Columns.Add("Series");
                }
                dtHeader.Columns.Add("DocDate");
                dtHeader.Columns.Add("TaxDate");
                dtHeader.Columns.Add("DocDueDate");
                dtHeader.Columns.Add("CardCode");
                dtHeader.Columns.Add("CardName");
                dtHeader.Columns.Add("U_SOType");
                dtHeader.Columns.Add("Comments");
                dtHeader.Columns.Add("Filler");
                dtHeader.Columns.Add("ToWhsCode");
                // UDF
                dtHeader.Columns.Add("U_ContactPerson");
                dtHeader.Columns.Add("U_DealerID");
                dtHeader.Columns.Add("U_Department");
                dtHeader.Columns.Add("U_TransferNBR");
                if (Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM")
                {
                    dtHeader.Columns.Add("U_Issue");
                    dtHeader.Columns.Add("U_DeliveryTime");
                    dtHeader.Columns.Add("U_BillNBR");
                }
                dtHeader.Columns.Add("U_XNB");
                dtHeader.Columns.Add("U_DebitNote");
                dtHeader.Columns.Add("U_SONBR");

                if (isDraft)
                {
                    dtHeader.Columns.Add("ObjType");
                }
                DataRow drHeader = dtHeader.NewRow();
                if (isDraft)
                {
                    drHeader["ObjType"] = "67";
                }
                if (!isDraft)
                {
                    drHeader["Series"] = 21;
                }
                drHeader["DocDate"] = Utils.AppConstants.ConvertToDate(txtPostingDate.Text).ToString("yyyyMMdd");
                drHeader["TaxDate"] = Utils.AppConstants.ConvertToDate(txtDocDate.Text).ToString("yyyyMMdd");
                drHeader["DocDueDate"] = Utils.AppConstants.ConvertToDate(this.txtDeliveryDate.Text).ToString("yyyyMMdd");
                drHeader["Comments"] = txtRemarks.Text;
                drHeader["CardCode"] = txtCustomerCode.Text;
                drHeader["CardName"] = txtCustomerName.Text;
                drHeader["U_SOType"] = ddl_TransferType.SelectedValue;
                drHeader["Filler"] = txtFromWhsCode.Text;
                drHeader["ToWhsCode"] = txtToWhsCode.Text;
                // UDF
                drHeader["U_ContactPerson"] = txtContactPerson.Text.Trim();
                drHeader["U_DealerID"] = Session[Utils.AppConstants.ID_Dealer].ToString();
                //drHeader["U_TransferNBR"] = this.txtTransferNumber.Text.Trim();
                drHeader["U_DebitNote"] = this.txtDebitNoteNo.Text.Trim();
                drHeader["U_Department"] = Session[Utils.AppConstants.U_Department].ToString();
                if (Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM")
                {
                    drHeader["U_Issue"] = this.ddl_Transfer.SelectedValue;
                    drHeader["U_DeliveryTime"] = this.ddlTime.SelectedValue.ToString();
                    drHeader["U_BillNBR"] = this.txtBillNumber.Text.Trim();
                }
                drHeader["U_SONBR"] = this.lblSONumber.Text + this.txtSONumber.Text;
                if (this.ddl_InternalTransfer.SelectedValue.ToString() == "XNB")
                {
                    drHeader["U_XNB"] = this.ddl_InternalTransfer.SelectedValue;
                }

                dtHeader.Rows.Add(drHeader);
                DataTable dtContents = (DataTable)Session["WTR1Table"];
                DocumentXML objInfo = new DocumentXML();
                DataSet ds = new DataSet("DS");
                dtHeader.TableName = tableHeader;
                dtContents.TableName = tableDetail;
                ds.Tables.Add(dtHeader.Copy());

                DataTable dt = new DataTable(tableDetail);
                dt.Columns.Add("LineNum");
                dt.Columns.Add("ItemCode");
                dt.Columns.Add("Dscription");
                dt.Columns.Add("U_Color");
                dt.Columns.Add("U_Model");
                dt.Columns.Add("FromWhsCod");
                dt.Columns.Add("WhsCode");
                dt.Columns.Add("Quantity");
                dt.Columns.Add("unitMsr");

                DataTable dtSRNT = null;
                if (!String.IsNullOrEmpty(hdnBaseType.Value))
                {
                    dt.Columns.Add("BaseEntry");
                    dt.Columns.Add("BaseLine");
                    dt.Columns.Add("BaseType");
                }
                int liNo = 0;
                foreach (DataRow dr in dtContents.Rows)
                {
                    DataRow rowNew = dt.NewRow();

                    rowNew["LineNum"] = liNo;
                    rowNew["ItemCode"] = dr["ItemCode"];
                    rowNew["Dscription"] = dr["Dscription"];
                    rowNew["U_Model"] = dr["U_Model"];
                    rowNew["U_Color"] = dr["U_Color"];
                    rowNew["FromWhsCod"] = txtFromWhsCode.Text;
                    rowNew["WhsCode"] = txtToWhsCode.Text;
                    rowNew["Quantity"] = dr["Quantity"];
                    rowNew["unitMsr"] = dr["unitMsr"];
                    if (!String.IsNullOrEmpty(hdnBaseType.Value))
                    {
                        rowNew["BaseEntry"] = dr["BaseEntry"];
                        rowNew["BaseLine"] = dr["BaseLine"];
                        rowNew["BaseType"] = dr["BaseType"];
                    }
                    BuildSRNT(ref dtSRNT, dr["ItemCode"].ToString(), dr["SysNumber"].ToString(), dr["DistNumber"].ToString(), dr["Indate"].ToString(), dr["Notes"].ToString(),
                              double.Parse(dr["Quantity"].ToString()), dr["WhsCode"].ToString(), ConvertDocType.Get2String(DocType.TRANSFER), txtTransferNo.Text, liNo.ToString());
                    dt.Rows.Add(rowNew);
                    liNo++;
                }

                ds.Tables.Add(GF.ResetFormatNumeric(dt, new string[] { "Quantity" }).Copy());
                if (!isDraft)
                {
                    ds.Tables.Add(dtSRNT.Copy());
                }

                string objType = string.Empty;
                if (!isDraft)
                {
                    objType = ConvertDocType.Get2String(DocType.TRANSFER);
                }
                else
                {
                    objType = "112";
                }
                return objInfo.ToXMLStringFromDS(objType, ds);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return "";
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="dtContent"></param>
        /// <returns></returns>
        private DataTable BuildContents(DataTable dtContent)
        {
            DataTable dt = new DataTable("WTR1");
            dt.Columns.Add("No");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("unitMsr");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("OpenQty");

            dt.Columns.Add("FromWhsCod");
            dt.Columns.Add("WhsCode");

            dt.Columns.Add("SysNumber");
            dt.Columns.Add("DistNumber");
            dt.Columns.Add("InDate");
            dt.Columns.Add("Notes");

            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("BaseType");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");

            if (dtContent != null)
            {
                foreach (DataRow dr in dtContent.Rows)
                {
                    DataRow row = dt.NewRow();
                    row["No"] = dr["No"];
                    row["ItemCode"] = dr["ItemCode"];
                    row["Dscription"] = dr["Dscription"];
                    row["U_Model"] = dr["U_Model"];
                    row["U_Color"] = dr["U_Color"];
                    row["unitMsr"] = dr["unitMsr"];
                    row["Quantity"] = dr["Quantity"];
                    row["OpenQty"] = dr["OpenQty"];
                    row["FromWhsCod"] = dr["FromWhsCod"];
                    row["WhsCode"] = dr["WhsCode"]; // To Whs Code

                    if (dr.Table.Columns.Contains("DistNumber"))
                    {
                        row["SysNumber"] = dr["SysNumber"];
                        row["DistNumber"] = dr["DistNumber"];
                        if (dr["InDate"].ToString().Length > 0)
                        {
                            row["InDate"] = dr["InDate"];
                        }
                        else
                        {
                            row["InDate"] = DateTime.Now;
                        }
                        row["Notes"] = dr["Notes"];
                    }
                    row["DocEntry"] = dr["DocEntry"];
                    row["LineNum"] = dr["LineNum"];
                    row["BaseType"] = dr["BaseType"];
                    row["BaseEntry"] = dr["BaseEntry"];
                    row["BaseLine"] = dr["BaseLine"];
                    dt.Rows.Add(row);
                }
            }
            return dt;
        }

        protected void LoadData(String itransId, string NewDocType)
        {
            DataTable dtHeader = new DataTable();
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            Transaction ts = new Transaction();
            DataSet returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, itransId, dbType);

            MasterData obj = new MasterData();

            DataSet dsWhs = obj.GetWarehouse(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());


            if (returnDoc == null)
            {
                itransId = "1";
                returnDoc = ts.GetMarketingDocument_ReturnDS(NewDocType, itransId, dbType);
                if (returnDoc != null || returnDoc.Tables.Count >= 2) dtHeader = returnDoc.Tables[0];
            }
            else
                dtHeader = returnDoc.Tables[0];

            if (returnDoc == null || returnDoc.Tables.Count < 2)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('No record found!','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
                return;
            }

            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            DataRow dr = dtHeader.Rows[0];

            this.txtTransferNo.Text = dr["DocNum"].ToString();
            this.txtCustomerCode.Text = dr["CardCode"].ToString();
            this.txtCustomerName.Text = dr["CardName"].ToString();
            this.txtFromWhsCode.Text = dr["Filler"].ToString();
            this.txtToWhsCode.Text = dr["ToWhsCode"].ToString();

            if (dtHeader.Columns.Contains("U_Issue"))
            {
                this.ddl_Transfer.SelectedValue = dr["U_Issue"].ToString();
            }
            if (dtHeader.Columns.Contains("U_XNB"))
            {
                this.ddl_InternalTransfer.SelectedValue = dr["U_XNB"].ToString();
            }
            if (dtHeader.Columns.Contains("U_SONBR"))
            {
                if (dr["U_SONBR"].ToString().Length > 0 && dbType == "VSM")
                {
                    this.txtSONumber.Text = dr["U_SONBR"].ToString().Substring(dr["U_SONBR"].ToString().Length - 2, 2);
                    this.lblSONumber.Text = dr["U_SONBR"].ToString().Substring(0, dr["U_SONBR"].ToString().Length - 2);
                }
                else
                {
                    this.txtSONumber.Text = dr["U_SONBR"].ToString();
                }
            }
                    
            this.txtRemarks.Text = dr["Comments"].ToString();
            if (dsWhs != null && dsWhs.Tables.Count > 0)
            {
                DataRow[] rfrom = dsWhs.Tables[0].Select("WhsCode='" + this.txtFromWhsCode.Text + "'");
                if (rfrom.Length > 0)
                {
                    this.txtFromWhsName.Text = rfrom[0]["WhsName"].ToString();
                }
                DataRow[] rto = dsWhs.Tables[0].Select("WhsCode='" + this.txtToWhsCode.Text + "'");
                if (rto.Length > 0)
                {
                    this.txtToWhsName.Text = rto[0]["WhsName"].ToString();
                }
            }

            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            this.txtDeliveryDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDueDate"], new CultureInfo("es-US")));
            txtContactPerson.Text = dr["U_ContactPerson"].ToString();
            ddl_TransferType.SelectedValue = dr["U_SOType"].ToString();
            txtRemarks.Text = dr["Comments"].ToString();
            if (dbType == "VSM")
            {
                this.txtDebitNoteNo.Text = dr["U_DebitNote"].ToString();
                this.txtBillNumber.Text = dr["U_BillNBR"].ToString();
                if (this.ddlTime.Items.FindByValue(dr["U_DeliveryTime"].ToString()) != null)
                {
                    this.ddlTime.SelectedValue = dr["U_DeliveryTime"].ToString();
                }
                if (dtHeader.Columns.Contains("U_XNB"))
                {
                    this.ddl_InternalTransfer.SelectedValue = dr["U_XNB"].ToString();
                }
            }
            if (NewDocType != ConvertDocType.Get2String(DocType.TRANSFER)) // It's copy from transfer request
            {
                SetScreenStatus("New");
            }
            else
            {
                SetScreenStatus("Closed");
            }
            hdnBaseType.Value = NewDocType;
            if (NewDocType != ConvertDocType.Get2String(DocType.TRANSFER)) // It's copy from transfer request
            {
                foreach (DataRow row in dtContents.Rows)
                {
                    row["BaseEntry"] = itransId;
                    row["BaseType"] = NewDocType;
                    row["BaseLine"] = row["LineNum"];
                    row["InDate"] = String.Format("{0:dd/MM/yyyy}", DateTime.Now);
                    row["Quantity"] = GF.FormatNumeric(row["OpenQty"].ToString(), "QtyDec");
                }
            }
            else
            {
                foreach (DataRow row in dtContents.Rows)
                {
                    row["InDate"] = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(row["InDate"], new CultureInfo("es-US")));
                    row["Quantity"] = GF.FormatNumeric(row["Quantity"].ToString(), "QtyDec");
                }
            }
            BindData(dtContents);
        }
        protected void LoadDraftData(string itransId)
        {
            DataTable dtHeader = new DataTable();
            string dbType = (string)Session[Utils.AppConstants.ID_Dealer] == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            GeneralFunctions GF = new GeneralFunctions(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());
            MasterData ts = new MasterData();
            DataSet returnDoc = ts.GetDraftMarketingDocument_ReturnDS(itransId, dbType, "DocEntry");

            MasterData obj = new MasterData();

            DataSet dsWhs = obj.GetWarehouse(dbType, Session[Utils.AppConstants.ID_Dealer].ToString());


            dtHeader = returnDoc.Tables[0];


            DataTable dtContents = BuildContents(returnDoc.Tables[1]);
            DataRow dr = dtHeader.Rows[0];

            this.txtTransferNo.Text = dr["DocNum"].ToString();
            this.txtCustomerCode.Text = dr["CardCode"].ToString();
            this.txtCustomerName.Text = dr["CardName"].ToString();
            this.txtFromWhsCode.Text = dr["Filler"].ToString();
            this.txtToWhsCode.Text = dr["ToWhsCode"].ToString();

            if (dtHeader.Columns.Contains("U_Issue"))
            {
                this.ddl_Transfer.SelectedValue = dr["U_Issue"].ToString();
            }
            if (dtHeader.Columns.Contains("U_XNB"))
            {
                this.ddl_InternalTransfer.SelectedValue = dr["U_XNB"].ToString();
            }
            //this.txtTransferNumber.Text = dr["U_TransferNBR"].ToString();
            this.txtSONumber.Text = dr["U_SONBR"].ToString();
            this.txtRemarks.Text = dr["Comments"].ToString();
            if (dsWhs != null && dsWhs.Tables.Count > 0)
            {
                DataRow[] rfrom = dsWhs.Tables[0].Select("WhsCode='" + this.txtFromWhsCode.Text + "'");
                if (rfrom.Length > 0)
                {
                    this.txtFromWhsName.Text = rfrom[0]["WhsName"].ToString();
                }
                DataRow[] rto = dsWhs.Tables[0].Select("WhsCode='" + this.txtToWhsCode.Text + "'");
                if (rto.Length > 0)
                {
                    this.txtToWhsName.Text = rto[0]["WhsName"].ToString();
                }
            }

            txtPostingDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDate"], new CultureInfo("es-US")));
            txtDocDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["TaxDate"], new CultureInfo("es-US")));
            this.txtDeliveryDate.Text = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dr["DocDueDate"], new CultureInfo("es-US")));
            txtContactPerson.Text = dr["U_ContactPerson"].ToString();
            ddl_TransferType.SelectedValue = dr["U_SOType"].ToString();
            txtRemarks.Text = dr["Comments"].ToString();
            //this.txtTransferNumber.Text = dr["U_TransferNBR"].ToString();
            this.txtSONumber.Text = dr["U_SONBR"].ToString();
            this.txtDebitNoteNo.Text = dr["U_DebitNote"].ToString();
            this.txtBillNumber.Text = dr["U_BillNBR"].ToString();
            this.ddlTime.SelectedValue = dr["U_DeliveryTime"].ToString();
            SetScreenStatus("New");

            foreach (DataRow row in dtContents.Rows)
            {
                row["InDate"] = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(row["InDate"], new CultureInfo("es-US")));
                row["Quantity"] = GF.FormatNumeric(row["Quantity"].ToString(), "QtyDec");
            }

            BindData(dtContents);
        }
        protected void LoadDefault()
        {
            this.txtPostingDate.Text =
            this.txtDocDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
            this.txtTransferNo.Text =
            this.txtCustomerCode.Text =
            this.txtCustomerName.Text =
            this.txtContactPerson.Text =
            this.txtRemarks.Text =
            this.hdnBaseType.Value = string.Empty;
            ddl_TransferType.SelectedValue = "1";

            DataTable dtContents = BuildContents(null);
            BindData(dtContents);
        }

        protected void ClearScreen()
        {
            DataTable dtHeader = new DataTable("OWTR");

            dtHeader.Columns.Add("Series");
            dtHeader.Columns.Add("DocStatus");
            dtHeader.Columns.Add("DocDate");
            dtHeader.Columns.Add("TaxDate");
            dtHeader.Columns.Add("CardCode");
            dtHeader.Columns.Add("CardName");
            dtHeader.Columns.Add("Filler");
            dtHeader.Columns.Add("WhsCode");
            dtHeader.Columns.Add("U_ContactPerson");
            dtHeader.Columns.Add("Comments");

            dtHeader.Rows.Add();

            CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
            txtPostingDate.Text.ToString(ci);
            txtDocDate.Text.ToString(ci);
            txtFromWhsCode.Text =
            txtFromWhsName.Text =
            txtToWhsCode.Text =
            txtToWhsName.Text =
            txtCustomerCode.Text =
            txtCustomerName.Text =
            txtContactPerson.Text =
            txtRemarks.Text =
            this.txtDebitNoteNo.Text =
            this.txtBillNumber.Text =
            this.lblSONumber.Text= 
            this.txtSONumber.Text =
            this.txtTransferNo.Text =
            hdnBaseType.Value = String.Empty;
            this.hdnDocEntry.Value = string.Empty;
            this.hdnIsDraft.Value = string.Empty;
            ddl_TransferType.SelectedValue = "1";
            this.txtDeliveryDate.Text = DateTime.Now.Date.ToString(Utils.AppConstants.DATE);

            DataTable dt = new DataTable("WTR1");
            dt.Columns.Add("No");
            dt.Columns.Add("ItemCode");
            dt.Columns.Add("Dscription");
            dt.Columns.Add("U_Model");
            dt.Columns.Add("U_Color");
            dt.Columns.Add("unitMsr");
            dt.Columns.Add("Quantity");
            dt.Columns.Add("OpenQty");

            dt.Columns.Add("FromWhsCod");
            dt.Columns.Add("WhsCode");

            dt.Columns.Add("SysNumber");
            dt.Columns.Add("DistNumber");
            dt.Columns.Add("InDate");
            dt.Columns.Add("Notes");

            dt.Columns.Add("DocEntry");
            dt.Columns.Add("LineNum");
            dt.Columns.Add("BaseType");
            dt.Columns.Add("BaseEntry");
            dt.Columns.Add("BaseLine");

            BindData(dt);
            SetScreenStatus("New");
        }

        protected void SetScreenStatus(string Status)
        {
            switch (Status)
            {
                case "New":
                    this.txtItemCode.Enabled=
                    btnAddItems.Enabled = false;
                    btnSave.Visible = true;
                    btnCopyFrom.Visible = true;
                    btnCancel.Visible = true;
                    hdnIsUpdate.Value = "false";
                    this.txtBillNumber.Enabled = false;
                    this.txtDeliveryDate.Enabled = false;
                    this.ImageButton1.Enabled = false;
                    this.ddlTime.Enabled = false;
                    break;

                case "Update":
                    this.txtItemCode.Enabled = 
                    btnAddItems.Enabled  = true;
                    btnSave.Visible = true;
                    btnCancel.Visible = true;
                    btnCopyFrom.Visible = true;
                    hdnIsUpdate.Value = "true";
                    this.txtBillNumber.Enabled = true;
                    this.txtDeliveryDate.Enabled = true;
                    this.ImageButton1.Enabled = true;
                    this.ddlTime.Enabled = true;
                    break;

                case "Close":
                    this.txtItemCode.Enabled = 
                    btnAddItems.Enabled  = false;
                    btnSave.Visible = false;
                    btnCopyFrom.Visible = true;
                    btnCancel.Visible = true;
                    break;
            }
        }

        protected void lnkOSRI_Click(object sender, EventArgs e)
        {
            try
            {
                GridViewRow gr = (GridViewRow)((DataControlFieldCell)((LinkButton)sender).Parent).Parent;
                Label lblItemCode = (Label)gr.FindControl("lblItemCode");
                string popup = "OpenOSRI('" + lblItemCode.Text + "','" + txtFromWhsCode.Text.Trim() + "')";
                ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "CallJS", popup, true);
            }
            catch (Exception ex)
            {
                this.lblError.Text = ex.Message;
                this.lblError.Visible = true;
            }
        }

        protected void btnLastRecord_Click(object sender, EventArgs e)
        {
            GetDefault fGetDefault = new GetDefault();
            string lsTransferNo = fGetDefault.GetMaxDocEntry(
                Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER,
                Session[Utils.AppConstants.ID_Dealer].ToString(),
                Utils.AppConstants.PARTS,
                ConvertDocType.Get2String(DocType.TRANSFER),
                TblHeaderName, HeaderKeyName
            );
            if (txtTransferNo.Text.CompareTo(lsTransferNo) != 0) Response.Redirect(CurrentPageUrl + "?itrans_id=" + lsTransferNo);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ddl_Transfer_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.ddl_Transfer.SelectedValue.ToString() == "XNB")
            {
                this.ddl_InternalTransfer.Enabled = true;
            }
            else
            {
                this.ddl_InternalTransfer.Enabled = false;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnDraft_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.txtSONumber.Text.Length == 0)
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Please input SO Number!" + "','');", true);
                    this.txtSONumber.Focus();
                    return;
                }
                string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
                String requestXML = _collectData(true);
                if (requestXML == "") return;

                Transaction ts = new Transaction();
                bool isUpdate = false;
                if (this.hdnDocEntry.Value.Length > 0 && this.hdnIsDraft.Value.Length > 0)
                {
                    isUpdate = true;
                }
                DataSet ds = ts.CreateMarketingDocument(requestXML, ((ulong)DocType.TRANSFER).ToString(), this.hdnDocEntry.Value, isUpdate, dbType);

                if ((int)ds.Tables[0].Rows[0]["ErrCode"] != 0)
                {
                    Session["errorMessage"] = ds.Tables[0].Rows[0]["ErrMsg"];
                    Session["requestXML"] = requestXML;
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + GeneralFunctions.UrlFullEncode(ds.Tables[0].Rows[0]["ErrMsg"].ToString()) + "','');", true);
                }
                else
                {
                    Session["successMessage"] = "Operation complete sucessful!";
                    ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + "Operation complete sucessful!" + "','');", true);
                    ClearScreen();
                }
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
            catch (Exception ex)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "OKErrors", "Main.setMasterMessage('" + ex.ToString() + "','');", true);
                ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "CloseLoading", "Dialog.hideLoader();", true);
            }
        }
        protected void txtItemCode_TextChanged(object sender, EventArgs e)
        {
            string dbType = Session[Utils.AppConstants.ID_Dealer].ToString() == "VSM" ? Utils.AppConstants.VSM : Utils.AppConstants.DEALER;
            MasterData obj = new MasterData();
            DateTime poDate = Utils.AppConstants.ConvertToDate(this.txtPostingDate.Text.Trim());
            DataTable tblITransRqst = (DataTable)Session["WTR1Table"];
            DataSet dsItem = obj.GetItemsByItemCodeList(dbType, Utils.AppConstants.ID_Dealer, "'" + this.txtItemCode.Text + "'");
            GetDefault defaultWS = new GetDefault();

            if (dsItem != null && dsItem.Tables.Count > 0)
            {
                foreach (DataRow dr in dsItem.Tables[0].Rows)
                {
                    DataSet defaultInfo = defaultWS.GetPartsDefaultLineInfo(dbType, Session[Utils.AppConstants.ID_Dealer].ToString(),
                        this.txtCustomerCode.Text, dr["ItemCode"].ToString(), 1, poDate, Utils.AppConstants.PARTS,"4");
                    if (defaultInfo != null && defaultInfo.Tables != null && defaultInfo.Tables[0].Rows.Count == 1)
                        tblITransRqst = AddNewItem(tblITransRqst, defaultInfo.Tables[0].Rows[0], dr["ItemCode"].ToString(), dr["ItemName"].ToString(), dr["U_Model"].ToString(), dr["U_Color"].ToString()
                            , defaultInfo.Tables[0].Rows[0]["UomCode"].ToString());
                    else continue;
                }
                this.txtItemCode.Text = "";
                //ReLoad Data
                BindData(tblITransRqst);
            }
        }
    }
}